#coding=utf-8

'''
@author: tongji
@contact: tongji@rekoo.com
'''
import sys
import traceback
from logger import Logger
from statistic_config import whitelist, callbacks

whitelist = [
             'main.views.func1',
             'main.views.func2',
             'main.views2.func10',
             'main.views2.func11',
             ]


def install(name=None):
    '''根据配置进行装饰'''
    
    for item in whitelist: # 从白名单中取需要装饰的视图函数
        try:
            itemlist = item.split('.')
            viewname = itemlist[-1] # 得到视图函数名称
            viewmodule = '.'.join(itemlist[:-1]) # 组合成视图函数所在的module名
            viewmodule = sys.modules[viewmodule] # 获取module对象
            view = getattr(viewmodule, viewname) # 获取函数对象
            decorate(viewmodule, view, key=item) # key是函数全局名字空间中的识别字符串
        except Exception, e:
            print 'Exception happened: ', e
        
def decorate(viewmodule, view):
    loggerobject = Logger()
    def new_view(request, *args, **kwargs): # 定义装饰后的视图函数
        loggerobject.get_data_before(request) # 获取视图函数执行之前的数据
        returndata = view(request, *args, **kwargs) # 执行视图函数
        loggerobject.get_data_after(request, funcname=key, callback=callbacks.get(key, None)) # 获取视图函数之后的数据，并提供对应的回调函数
        loggerobject.write() # 将日志写入udpserver 或者 scribeserver
        return returndata

    setattr(viewmodule, view.__name__, new_view) # 用装饰后的函数替换原来的视图函数
    print 'SUCCESSFULLY DECORATED VIEW ', view.__name__